package com.coocaa.app.lib.cleaner.deleter.utils;

import java.io.File;
import java.io.IOException;

/**
 * Created by Eric on 2017/4/13.
 */

public class FileUtils {

//    public static boolean deleteFile(String path){
//        return deleteFile(new File(path));
//    }
//
//    public static boolean deleteFile(File dir) {
//        if (dir.exists()) {
//            if (dir.isDirectory()) {
//                String[] children = dir.list();
//                //递归删除目录中的子目录下
//                for (int i = 0; i < children.length; i++) {
//                    boolean success = deleteFile(new File(dir, children[i]));
//                    if (!success) {
//                        return false;
//                    }
//                }
//            }
//            // 目录此时为空，可以删除
//            return dir.delete();
//        }
//        return false;
//    }

    public static boolean deleteFile(String path) {
        File dir = new File(path);
        if (dir.exists()) {
            String chmodCMD = "";
            String rmCMD = "";
            if (dir.isDirectory()) {
                chmodCMD = "chmod -R 777 " + path;
                rmCMD = "rm -rf " + path;
            } else {
                chmodCMD = "chmod 777 " + path;
                rmCMD = "rm " + path;
            }

            try {
                Runtime.getRuntime().exec(chmodCMD);
                Runtime.getRuntime().exec(rmCMD);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

//            if (dir.isDirectory()) {
//                String cmd = "rm -rf " + path;
//                try {
//                    Runtime.getRuntime().exec(cmd);
//                    return true;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    return false;
//                }
//            }
//            return dir.delete();
        }
        return false;
    }

    public static long getFileSize(String dir) {
        return getFileSize(new File(dir));
    }

    public static long getFileSize(File file) {
        if (!file.exists())
            return 0;
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getFileSize(child);
        return total;

    }
}
